﻿// Copyright (c) 2014 Converter Systems LLC

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;

namespace ConverterSystems.Workstation
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public sealed partial class App
    {
        private AppBootstrapper _bootstrapper;

        protected override void OnStartup(StartupEventArgs e)
        {
#if !(DEBUG)
            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
#endif
            _bootstrapper = new AppBootstrapper();
            _bootstrapper.Run();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            _bootstrapper.Dispose();
        }

#if !(DEBUG)
        private void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            var ex = e.Exception;
            if (ex != null)
            {
                Trace.TraceError(ex.ToString());
            }
        }

        private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                Trace.TraceError(ex.ToString());
            }
            if (!e.IsTerminating)
            {
                MessageBox.Show(ConverterSystems.Workstation.Properties.Resources.UnhandledException, ConverterSystems.Workstation.Properties.Resources.ApplicationError, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
#endif
    }
}